<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\goods\controller;

use cmf\controller\AdminBaseController;
use app\goods\model\GoodsModel;
use app\goods\service\GoodsService;
use app\goods\model\GoodsCategoryModel;
use think\Db;
use app\admin\model\ThemeModel;

class AdminGoodsController extends AdminBaseController
{
    /**
     * 产品列表
     * @adminMenu(
     *     'name'   => '产品管理',
     *     'parent' => 'goods/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $param                = $this->request->param();
        $categoryId           = $this->request->param('category', 0, 'intval');
        $param['sort_by']     = $this->request->param('sort_by','','trim');
        $param['list_order']  = $this->request->param('list_order','DESC','trim');

        $goodsService = new GoodsService();
        $data         = $goodsService->adminGoodsList($param);
        $goods        = $data->items();

        // $siteConfig = cmf_get_site_info();
        // $authMode   = $siteConfig['auth_mode'];
        //是否细分栏目操作权限模式
        /**
         * 产品是否拥有编辑和删除的权限
         * 只要该产品所属的某个分类中拥有编辑或删除权限即可以操作该产品
         */
        $goodsEdit   = cmf_auth_check(cmf_get_current_admin_id(), 'goods/admingoods/edit');
        $goodsDelete = cmf_auth_check(cmf_get_current_admin_id(), 'goods/admingoods/delete');

        $userId = cmf_get_current_admin_id();
        $roleId = session('ROLE_ID');
        foreach ($goods as $k => &$v) {
            // 若为超级管理员可编辑和删除
            if( $roleId == 1 ){
                $v['is_edit'] = $v['is_delete'] = 1;
            }else{
                $v['is_edit'] = $v['is_delete'] = 0;
                // 若不是超级管理员，仅可操作自己添加的产品
                // if( $v['user_id'] != $userId )      continue;
                if( !$goodsEdit && !$goodsDelete )  continue;

                // 该产品所属的所有分类
                $categoryIds  = db('goods_category_relate')->where('goods_id', $v['goods_id'])->column('category_id');
                if( $goodsEdit ){
                    //产品审核状态为未通过才能编辑产品，待审核及审核通过均不允许编辑
                    // if( $v['post_status'] === -1 ){
                        // 该产品所属的某个分类是否拥有编辑的操作权限
                        $v['is_edit']   = check_cat_priv($categoryIds, 'edit', 'goods_category');
                    // }
                }

                if( $goodsDelete ){
                    // 该产品所属的某个分类是否拥有删除的操作权限
                    $v['is_delete']   = check_cat_priv($categoryIds, 'delete', 'goods_category');
                }
            }
        }

        //向分页追加请求参数
        $data->appends($param);

        $goodsCategoryModel = new GoodsCategoryModel();
        $idList             = get_cat_priv('init', 'goods_category'); //获取该角色可查看的栏目分类id
        $categoryTree       = $goodsCategoryModel->adminCategoryTree($categoryId, 0, $idList);

        //当前排序依据
        $sort_flag  = sort_flag($param);
        $this->assign($sort_flag['tag'], $sort_flag['img']);

        //获取列表项
        $listItem = get_list_item_column('goods');
        $this->assign('list_item', $listItem);

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign("filter",$param);
        $this->assign('goods', $goods);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /**
     * 添加产品
     * @adminMenu(
     *     'name'   => '添加产品',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加产品',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        //当前分类信息
        $categoryId = $this->request->param('category', 0, 'intval');

        //判断该分类下是否拥有添加产品权限
        if( !empty($categoryId) ){
            if( !check_cat_priv($categoryId, 'add', 'goods_category') ){
                $this->error(lang('NO_AUTH'));
            }
        }

        $category   = Db::name('GoodsCategory')
                   -> field('id,name,parent_id,list_tpl,thumb_size')
                   -> find($categoryId);
        $category['name'] = empty($category['name']) ? '' :$category['name'];
        $category['id']   = empty($category['id']) ? '' :$category['id'];

        //分类缩略图推荐尺寸
        $category['thumb_size'] = get_thumb_size($categoryId, 'goods_category');
        
        //分类树(文章所属分类-单选)
        $goodsCategoryModel = new GoodsCategoryModel();
        $idList              = get_cat_priv('add', 'goods_category');
        $categoryTree        = $goodsCategoryModel->adminCategoryTree($categoryId, 0, $idList);
        $this->assign('category_tree', $categoryTree);

        //获取产品详情页模版列表
        $themeModel      = new ThemeModel();
        $goodsThemeFiles = $themeModel->getActionThemeFiles('goods/Details/index');

        // 产品类型列表
        $goods_type_list = goods_type_list();
        $this->assign('goods_type_list', $goods_type_list);

        $this->assign('goods_theme_files', $goodsThemeFiles);   //产品详情页模版列表
        $this->assign('category', $category);                       //分类信息

        return $this->fetch();
    }

    /**
     * 添加产品提交
     * @adminMenu(
     *     'name'   => '添加产品提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加产品提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminGoods');
            if ($result !== true) {
                $this->error($result);
            }

            $categories = $post['categories'];

            if($categories){
                $categories = explode(',',$categories);
            }

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            // 附件
            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $goodsModel = new GoodsModel();
            $goodsModel->adminAddGoods($data['post'], $data['post']['categories'], $data);
            
            //操作日志
            admin_log($post['goods_name'], 'add', 'goods');

            $this->success('添加成功!', url('AdminGoods/edit', ['id' => $goodsModel->goods_id]));
        }

    }

    /**
     * 编辑产品
     * @adminMenu(
     *     'name'   => '编辑产品',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑产品',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');

        if( session('ROLE_ID') != 1 ){
            //获取关联的分类id
            $cat_id_list = Db::name('goods_category_relate')->where(['goods_id'=>$id])->column('category_id');
            if( !check_cat_priv($cat_id_list, 'edit', 'goods_category') ){
                $this->error(lang('NO_AUTH'));
            }
        }

        //产品信息
        $goodsModel = new GoodsModel();
        $post       = $goodsModel->where('goods_id', $id)->find();

        //产品所属分类信息
        $Categories  = $post
                    -> categories()
                    -> alias('a')
                    -> field('a.name,a.id,thumb_size,list_tpl,parent_id')
                    -> select();
        
        foreach ($Categories as $k => $v) {
            $postCategoryIds[] = $v['id'];          //产品所属分类id集合
            $postCategories[]  = $v['name'];        //产品所属分类名集合

            if( empty($v['thumb_size']) ){
                $Categories[$k]['thumb_size'] = get_thumb_size($v['parent_id'], 'goods_category');
            }
        }

        // 产品类型列表
        $goods_type_list = goods_type_list($post['goods_type']);
        $this->assign('goods_type_list', $goods_type_list);
        $this->assign('goods_attr_html', build_attr_html($post['goods_type'], $id));
      
        //分类树(文章所属分类-单选)
        $goodsCategoryModel = new GoodsCategoryModel();
        $idList             = get_cat_priv('edit', 'goods_category');
        $categoryTree       = $goodsCategoryModel->adminCategoryTree($Categories[0]['id'], 0, $idList);
        $this->assign('category_tree', $categoryTree);

        //详情页模版列表
        $themeModel        = new ThemeModel();
        $goodsThemeFiles = $themeModel->getActionThemeFiles('goods/Details/index');
    
        $this->assign('post', $post);                               //产品信息
        $this->assign('goods_theme_files', $goodsThemeFiles);   //详情页模版列表
        $this->assign('categories', $Categories);                   //产品信息
        // $this->assign('post_categories', $postCategories);          //产品所属分类名
        // $this->assign('post_category_ids', $postCategoryIds);       //产品所属分类id

        // $this->assign("field_list", $field_list);                   //该分类类型的字段
        // $this->assign("field_status_list", $field_status_list);     //该分类类型的状态字段

        return $this->fetch();
    }

    /**
     * 编辑产品提交
     * @adminMenu(
     *     'name'   => '编辑产品提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑产品提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminGoods');
            if ($result !== true) {
                $this->error($result);
            }

            $categories = $post['categories'];
          
            if($categories){
                $categories = explode(',',$categories);
            }

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            
            $goodsModel = new GoodsModel();
            $goodsModel->adminEditGoods($data['post'], $data['post']['categories'], $data);


            //操作日志
            admin_log($post['goods_name'], 'edit', 'goods');

            $this->success('保存成功!');

        }
    }

    /**
     * 产品删除
     * @adminMenu(
     *     'name'   => '产品删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $param      = $this->request->param();
        $goodsModel = new GoodsModel();
        $siteConfig = cmf_get_site_info();
        $authMode   = $siteConfig['auth_mode'];

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');

            if( session('ROLE_ID')!=1 ){
                //获取关联的分类id
                $cat_id_list = Db::name('goods_category_relate')->where(['goods_id'=>$id])->column('category_id');
                //只要产品所属的某个分类拥有删除权限，即可以操作该产品
                if( !check_cat_priv($cat_id_list, 'delete', 'goods_category') ){
                    $this->error(lang('NO_AUTH'));
                }
            }

            $result       = $goodsModel->where(['goods_id' => $id])->find();
            $data         = [
                'object_id'   => $result['goods_id'],
                'create_time' => time(),
                'table_name'  => 'goods',
                'name'        => $result['goods_name'],
                'site_id'     => $result['site_id'],
            ];
            $resultPortal = $goodsModel
                ->where(['goods_id' => $id])
                ->update(['delete_time' => time()]);

            if ($resultPortal) {
                Db::name('recycleBin')->insert($data);
            }

            //操作日志
            admin_log($result['goods_name'], 'delete', 'goods');

            $this->success("删除成功！", '');
        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $recycle = $goodsModel->where(['goods_id' => ['in', $ids]])->select();
            $result  = false;

            //若是超级管理员，直接删除接收到的产品id;否则只删除该角色拥有的分类删除权限下的产品
            if( session('ROLE_ID')==1 ){
                $result  = $goodsModel->where(['goods_id' => ['in', $ids]])->update(['delete_time' => time()]);
            }else{
                $user_id = cmf_get_current_admin_id();
                foreach($recycle as $key=>$value){

                    if( $user_id == $value['user_id'] ){
                        //产品所属的所有分类id
                        $cat_id_list = Db::name('goods_category_relate')->where(['goods_id'=>$value['goods_id']])->column('category_id');

                        //检查是否拥有删除权限，只要产品所属分类的某个分类拥有删除权限，则可以操作该产品
                        if( check_cat_priv($cat_id_list, 'delete', 'goods_category') ){
                            //组合新的要删除的产品id
                            $new_ids[] = $value['goods_id'];
                        }else{
                            unset($recycle[$key]);
                        }
                    }else{
                        unset($recycle[$key]);
                    }
                }

                if( !empty($new_ids) ){
                    $result  = $goodsModel->where(['goods_id' => ['in', $new_ids]])->update(['delete_time' => time()]);
                }
            }

                
            if ($result) {
                foreach ($recycle as $value) {
                    $data = [
                        'object_id'   => $value['goods_id'],
                        'create_time' => time(),
                        'table_name'  => 'goods',
                        'name'        => $value['goods_name'],
                        'site_id'     => $value['site_id'],
                    ];
                    Db::name('recycleBin')->insert($data);
                }

                //操作日志
                admin_log('', 'batch_delete', 'goods');

                $this->success("删除成功！", '');
            }else{
                $this->success("删除失败！", '');
            }
        }
    }

    /**
     * 产品发布
     * @adminMenu(
     *     'name'   => '产品发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品发布',
     *     'param'  => ''
     * )
     */
    // public function publish()
    // {
    //     $param           = $this->request->param();
    //     $goodsModel = new GoodsModel();

    //     if (isset($param['ids']) && isset($param["yes"])) {
    //         $ids = $this->request->param('ids/a');

    //         $goodsModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

    //         $this->success("发布成功！", '');
    //     }

    //     if (isset($param['ids']) && isset($param["no"])) {
    //         $ids = $this->request->param('ids/a');

    //         $goodsModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

    //         $this->success("取消发布成功！", '');
    //     }

    // }

    /**
     * 产品发布
     * @adminMenu(
     *     'name'   => '产品发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品发布',
     *     'param'  => ''
     * )
     */
    public function openshow()
    {
        $param           = $this->request->param();
        
        $ids = $this->request->param('ids/a');

        $where = [
            'a.goods_id'     => ['in', $ids],
        ];

        if( session('ROLE_ID') != 1 ){
            $where['b.post_status'] = 99;
        }

        if (isset($param['ids']) && isset($param["yes"])) {
            db('goods_category_relate')
            ->alias('a')
            ->join('goods b','a.goods_id = b.goods_id')
            ->where($where)
            ->update(['a.is_show' => 1]);

            //操作日志
            admin_log('', '', 'goods_open_show_yes');

            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            db('goods_category_relate')
            ->alias('a')
            ->join('goods b','a.goods_id = b.goods_id')
            ->where($where)
            ->update(['a.is_show' => 0]);

            //操作日志
            admin_log('', '', 'goods_open_show_no');

            $this->success("取消发布成功！", '');
        }

    }

    /**
     * 产品置顶
     * @adminMenu(
     *     'name'   => '产品置顶',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品置顶',
     *     'param'  => ''
     * )
     */
    public function top()
    {
        $param           = $this->request->param();
        $goodsModel = new GoodsModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $goodsModel->where(['goods_id' => ['in', $ids]])->update(['is_top' => 1]);

            //操作日志
            admin_log('', '', 'goods_top_yes');

            $this->success("置顶成功！", '');

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $goodsModel->where(['goods_id' => ['in', $ids]])->update(['is_top' => 0]);

            //操作日志
            admin_log('', '', 'goods_top_no');

            $this->success("取消置顶成功！", '');
        }
    }

    /**
     * 产品推荐
     * @adminMenu(
     *     'name'   => '产品推荐',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品推荐',
     *     'param'  => ''
     * )
     */
    public function recommend()
    {
        $param           = $this->request->param();
        $goodsModel = new GoodsModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');

            $goodsModel->where(['goods_id' => ['in', $ids]])->update(['recommended' => 1]);

            //操作日志
            admin_log('', '', 'goods_recommend_yes');

            $this->success("推荐成功！", '');

        }
        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');

            $goodsModel->where(['goods_id' => ['in', $ids]])->update(['recommended' => 0]);

            //操作日志
            admin_log('', '', 'goods_recommend_no');

            $this->success("取消推荐成功！", '');

        }
    }

    /**
     * 产品排序
     * @adminMenu(
     *     'name'   => '产品排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '产品排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        parent::listOrders(Db::name('goods_category_relate'));

        //操作日志
        admin_log('', '', 'goods_list_order');

        $this->success("排序更新成功！", '');
    }

    // 产品批量移动
    public function move(){
        if ( $this->request->isPost()){
            $ids         = $this->request->param('ids/s');
            $old_cat_id  = $this->request->param('old_cat_id', 0, 'intval');
            $category_id = $this->request->param('categories', 0, 'intval');

            if(!empty($ids) && !empty($old_cat_id) && !empty($category_id)){

                if( $old_cat_id != $category_id ){
                    $ids = explode(',', $ids);
                    foreach ($ids as $id){
                        Db::name('GoodsCategoryRelate')->where(['goods_id'=>$id,'category_id'=>$old_cat_id])->delete();
                        $find_relation_count=Db::name('GoodsCategoryRelate')->where(['goods_id'=>$id,'category_id'=>$category_id])->count();
                        if($find_relation_count==0){
                            Db::name('GoodsCategoryRelate')->insert(['goods_id'=>$id,'category_id'=>$category_id]);
                        }
                    }
                }

                //操作日志
                admin_log('', '', 'goods_move');

                $this->success("移动成功！");
            }
        }else{
            $goodsCategoryModel = new GoodsCategoryModel();
            $categoryTree        = $goodsCategoryModel->adminCategoryTree();
            $this->assign('category_tree', $categoryTree);
            return $this->fetch();
        }
    }
    
    // 产品批量复制
    public function copy(){
        if ( $this->request->isPost()){
            $ids         = $this->request->param('ids/s');
            $category_id = $this->request->param('categories', 0, 'intval');

            if( !empty($ids) && !empty($category_id) ){
                $goodsCategoryModel = new GoodsCategoryModel();
                $ids         = explode(',', $ids);
                $uid         = cmf_get_current_admin_id();
                $term_count  = $goodsCategoryModel->where('id', $category_id)->count();

                if( $term_count == 0 ){
                    $this->error('分类不存在！');
                }
                
                $goodsModel = new GoodsModel();
                $data            = array();
                foreach ($ids as $id){
                    $find_post = $goodsModel->find($id)->toArray();
                    if($find_post){
                        unset($find_post['goods_id']);
                        $find_post['user_id']        = $uid;
                        $find_post['published_time'] = time();
                        $find_post['update_time']    = time();
                        $find_post['create_time']    = time();
                        $find_post['more']           = json_encode($find_post['more']);
                        $goods_id                     = $goodsModel->insertGetId($find_post);
                        if($goods_id>0){
                            array_push($data, ['goods_id'=>$goods_id, 'category_id'=>$category_id]);
                        }
                    }
                }

                if ( Db::name('GoodsCategoryRelate')->insertAll($data) !== false) {

                    //操作日志
                    admin_log('', '', 'goods_copy');

                    $this->success("复制成功！");
                } else {
                    $this->error("复制失败！");
                }
            }
        }else{
            $goodsCategoryModel = new GoodsCategoryModel();
            $categoryTree        = $goodsCategoryModel->adminCategoryTree();
            $this->assign('category_tree', $categoryTree);
            return $this->fetch();
        }
    }

    // 切换商品类型
    public function getAttr(){
        $goods_id   = $this->request->param('goods_id', 0, 'intval');
        $goods_type = $this->request->param('goods_type', 0, 'intval');

        $content           = build_attr_html($goods_type, $goods_id);
        $result['content'] = $content;

        return json($result);
    }

   /**
    * 待审核产品列表
    * @adminMenu(
    *     'name'   => '待审核内容',
    *     'parent' => 'index',
    *     'display'=> true,
    *     'hasView'=> true,
    *     'order'  => 10000,
    *     'icon'   => '',
    *     'remark' => '待审核产品列表',
    *     'param'  => ''
    * )
    */
   public function checkList()
   {
        $param      = $this->request->param();
        $categoryId = $this->request->param('category', 0, 'intval');
        $stepIndex  = $this->request->param('step_index', 1, 'intval');

        $param['sort_by']     = $this->request->param('sort_by','goods_id','trim');
        $param['list_order']  = $this->request->param('list_order','DESC','trim');

        $goodsCategoryModel = new GoodsCategoryModel();
 
        //当前分类信息
        if( empty($categoryId) ){
            //默认分类ID
            $category = $goodsCategoryModel
                   -> field('id,audit_id')
                   -> where('delete_time',0)
                   -> where('audit_id','>',0)
                   -> order("id ASC")
                   -> find();
            $categoryId = $param['category'] =$category['id'];
        }else{
            $category = $goodsCategoryModel
                   -> field('id,audit_id')
                   -> where('id',$categoryId)
                   -> order("id ASC")
                   -> find();
        }

        //分类树
        $categoryTree = $goodsCategoryModel->adminCategoryTree($categoryId, 0, 0, 1);

        $noAuthKey = $authKey = [];
        // 分类有选择审核流程
        if( !empty($category['audit_id']) ){
            //角色id
            $role_id  = session('ROLE_ID');
            //该流程下的所有审核步骤
            $stepList = Db::name('audit_flow_step')
                   -> where('audit_id',$category['audit_id'])
                   -> order('step_index asc')
                   -> select()
                   -> toArray();

            // 审核流程下存在审核步骤
            if( !empty($stepList) ){

                foreach ($stepList as $k => $v) {
                    //若当前登录的不是超级管理员，判断是否拥有该步骤的权限
                    if( $role_id!=1 ){
                        //分割拥有该步骤权限的角色id
                        $auth_role_id = explode(',',$v['auth_role_id']);

                        if( !in_array($role_id, $auth_role_id) ){
                            $noAuthKey[] = $v['step_index'];  //没有权限的审核步骤
                        }
                    }

                    //构建数组，用于创建审核步骤select框
                    $haveStep[$v['step_index']] = $v['step_name'];
                }

                $allAuthKey = array_keys($haveStep);                  //所有审核步骤
                $authKey    = array_diff($allAuthKey, $noAuthKey);    //有权限的审核步骤

                //若当前选择的步骤序号大于该流程下最大的步骤序号，则重置为1(第一个审核步骤)
                $lastIndex = end($allAuthKey);
                $stepIndex = ($stepIndex > $lastIndex) ? 1 : $stepIndex;

                //若当前步骤在非拥有权限步骤的集合中
                if( in_array($stepIndex, $noAuthKey) ){
                    //若拥有权限步骤集合不为空，重置当前步骤;否则清空步骤，不查询待审核数据
                    $stepIndex = !empty($authKey) ? current($authKey) : 0;
                }

                //待审核产品列表
                if( !empty($haveStep) ){
                   $param['post_status'] = ['=',$stepIndex];
                   $goodsService = new GoodsService();
                   $data         = $goodsService->adminGoodsList($param);
                   $goods        = $data->items();

                   /**
                    * 产品是否拥有编辑和删除的权限
                    * 只要该产品所属的某个分类中拥有编辑或删除权限即可以操作该产品
                    */
                   $goodsEdit = cmf_auth_check(cmf_get_current_admin_id(), 'goods/admingoods/edit');

                   $userId = cmf_get_current_admin_id();
                   foreach ($goods as $k => &$v) {
                       //审核节点
                       $audit_id             = $goodsCategoryModel->where('id',$v['category_id'])->value('audit_id');
                       $v['audit_step_name'] = $auditFlows[$audit_id][$v['post_status']];

                       // 若为超级管理员可编辑和删除
                       if( $roleId == 1 ){
                           $v['is_edit'] = 1;
                       }else{
                           $v['is_edit'] = 0;
                           // 若不是超级管理员，仅可操作自己添加的产品
                           // if( $v['user_id'] != $userId )  continue;
                           if( !$goodsEdit )               continue;

                           // 该产品所属的所有分类
                           $categoryIds  = db('goods_category_relate')->where('goods_id', $v['goods_id'])->column('category_id');
                           if( $goodsEdit ){
                               //产品审核状态为未通过才能编辑产品，待审核及审核通过均不允许编辑
                               // if( $v['post_status'] === -1 ){
                                   // 该产品所属的某个分类是否拥有编辑的操作权限
                                   $v['is_edit']   = check_cat_priv($categoryIds, 'edit', 'goods_category');
                               // }
                           }
                       }
                   }
                   
                   //追加参数，用于分页
                   $data->appends($param);
                   $this->assign('goods', $goods);
                   $this->assign('page', $data->render());
                }
            }
        }

       $haveStepList = html_options($haveStep, $stepIndex, $noAuthKey);
       $this->assign('have_step_list', $haveStepList);     //拥有的步骤列表

       $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
       $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
       // $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');

       $this->assign('step_index', $stepIndex);            //当前所在步骤
       $this->assign('category_tree', $categoryTree);      //分类树
       $this->assign('category', $categoryId);             //当前分类id
       
       //当前排序依据
       $sort_flag  = sort_flag($param);
       $this->assign($sort_flag['tag'], $sort_flag['img']);
       $this->assign("filter",$param);

       return $this->fetch();
   }

    //通过审核
    public function pass(){
        $categoryId = $this->request->param('category', 0, 'intval');
        $stepIndex  = $this->request->param('step_index', 1, 'intval');

        if( $stepIndex == -1 ){
            parent::passStep(Db::name('goods'), $stepIndex);
            //操作日志
            admin_log('', '', 'goods_not_pass');
        }else{
            //获取当前分类所使用的审核流程
            $goodsCategoryModel = new GoodsCategoryModel();
            $audit_id = $goodsCategoryModel->where('id',$categoryId)->value('audit_id');

            //该流程下的所有审核步骤
            $maxStepIndex = Db::name('audit_flow_step')
                         -> where('audit_id',$audit_id)
                         -> max('step_index');

            //是否已超过最终步骤
            if( $maxStepIndex>$stepIndex ){
                $status = $stepIndex+1;
            } else {
                $status = 99;
            }
            
            // 修改产品审核状态
            parent::passStep(Db::name('goods'), $status);

            //操作日志
            admin_log('', '', 'goods_pass');
        }
        
        $this->success("操作成功！",'');
    }

    //替换
    public function replace(){
        $data = $this->request->param('data', '', 'trim');
        $data = explode(',', $data);
        $results = array();
        foreach ($data as $key => $value) {
            $test = explode(':', $value);
            $results = cmf_replaceSensitive2($test);
            if($results){
                $result[$key] = $results;
            }
        }

        if(empty($result)){
            $result[0] = 1;
        }

        return $result;
    }

    /**
     *
     * 导出Excel
     */
    public function export(){//导出Excel

        $filter = $this->request->param();
        $order  = "b.category_id ASC, b.list_order DESC, a.published_time DESC, b.goods_id DESC";
        $where  = [
            'a.create_time' => ['>=', 0],
            'a.delete_time' => 0,
        ];

        //是否指定分类
        $category = empty($filter['category']) ? 0 : intval($filter['category']);
        if( empty($category) ){
            //获取方式排序为分类树形式的所有分类id
            $goodsCategoryModel = new GoodsCategoryModel();
            $categoryIds         = $goodsCategoryModel->adminCategoryTableTree(0,"\$id,");
            $categoryIds         = explode(',', $categoryIds);

            // 若不是超级管理员，只获取有导出权限的分类
            if( session('ROLE_ID') != 1 ){
                //获取有导出权限的分类
                $operateIds  = get_cat_priv('export', 'goods_category');
                if( empty($operateIds) ){
                    $this->error(lang('NO_AUTH'));
                }

                //有权限的分类数组和所有分类数组取交集，用于得到有权限的分类id集并保持排序
                $categoryIds = array_intersect($operateIds, $categoryIds);
            }
            $where['b.category_id'] = ['in', $categoryIds];
        }else{
            // 该角色当前分类是否有导出权限
            if( !check_cat_priv($category, 'export', 'goods_category') ){
                $this->error(lang('NO_AUTH'));
            }
            $where['b.category_id'] = ['eq', $category];
        }

        $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
        $endTime   = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
        if (!empty($startTime) && !empty($endTime)) {
            $where['a.published_time'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['a.published_time'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['a.published_time'] = ['<= time', $endTime];
            }
        }

        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if (!empty($keyword)) {
            $where['a.goods_name'] = ['like', "%$keyword%"];
        }


        $join = [
            ['__GOODS_CATEGORY_RELATE__ b', 'a.goods_id = b.goods_id'],
            ['__GOODS_CATEGORY__ c', 'b.category_id = c.id'],
            ['__USER__ u', 'a.user_id = u.id'],
        ];

        $goodsModel = new GoodsModel();
        $data = $goodsModel->alias('a')->field($field)
            ->field('goods_name, c.name, u.user_login as author, post_hits, a.published_time, a.update_time, c.id')
            ->join($join)
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        if( empty($categoryIds) ){
            // 指定了分类
            foreach ($data as $k => &$v) {
                $v['published_time'] = date('Y/m/d H:i', $v['published_time']);
                $v['update_time']    = date('Y/m/d H:i', $v['update_time']);
            }
            $xlsData = $data;
        }else{
            // 没有指定分类时，按照分类树的排序，创建要导出的数据数组
            foreach ($categoryIds as $k => $v) {
                foreach ($data as $key => $val) {
                    if( $v == $val['id'] ){
                        $val['published_time'] = date('Y/m/d H:i', $val['published_time']);
                        $val['update_time']    = date('Y/m/d H:i', $val['update_time']);
                        $xlsData[] = $val;
                    }
                }
            }
        }
        
        //操作日志
        admin_log('', '', 'goods_export');

        $xlsName  = "产品点击量统计_".date('YmdHis');
        $xlsCell  = array(
            array('goods_name',lang('goods_name')),
            array('name','分类'),
            array('author','发布人'),
            array('post_hits','点击量'),
            array('published_time','发布时间'),
            array('update_time','更新时间'),
        );

        exportExcel($xlsName,$xlsCell,$xlsData);
    }
}

/**
 * 根据属性数组创建属性的表单
 *
 * @access  public
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  string
 */
function build_attr_html($cat_id, $goods_id = 0 , $bar_code = 0)
{
    $attr = get_attr_list($cat_id, $goods_id);
    $html = '<table width="100%" id="attrTable" class="table">';
    $spec = 0;

    foreach ($attr AS $key => $val)
    {
        $html .= "<tr><th class='control-label '>";
        if($val[attr_txm] > 0){
            $html.="<a href=\"javascript:showNotice('attr_".$val['attr_id'] ."');\" title=\"点击此处查看提示信息\"><img src=\"images/notice.gif\" alt=\"点击此处查看提示信息\" border=\"0\" height=\"16\" width=\"16\"></a>";
        }
        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
        {
            $html .= ($spec != $val['attr_id']) ?
                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
            $spec = $val['attr_id'];
        }
    
                        
         $html.=$val[attr_name]."</th><td class=''><input type='hidden' name='attr_id_list[]' value='$val[attr_id]' txm='$val[attr_txm]' class='ctxm_$val[attr_txm]' />";

        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input class="form-control" name="attr_value_list[]" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="attr_value_list[]" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
        }
        else
        {
            if($val[attr_txm] > 0){
                $html .= '<select class=form-control attr_num_'.$val[attr_id].' name="attr_value_list[]" onchange="getType('.$val[attr_txm].','.$cat_id.','. $this.value.','.$goods_id.')">';
            }else{
                $html .= '<select class=form-control attr_num_'.$val[attr_id].' name="attr_value_list[]" >';
            }
            $html .= '<option value="">' .lang('select_please'). '</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= ($val['attr_value'] != $opt) ?
                    '<option value="' . $opt . '">' . $opt . '</option>' :
                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
            }
            $html .= '</select> ';
           
        }
      
        // $html .= ($val['attr_type'] == 1 || $val['attr_type'] == 2) ?
        //     $GLOBALS['_LANG']['spec_price'].' <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
        //     ' <input type="hidden" name="attr_price_list[]" value="0" />';
        
        if($val[attr_txm] > 0){
            $html .="<span class=\"notice-span\" style=\"display:block\" id=\"attr_".$val['attr_id'] ."\">此属性是条码属性，您只有选择完所有的条码属性后才能输入“组合属性”的对应条形码</span>";
        }
        $html .= '</td></tr>';
    }
     $html .= '</table>';

    // if($bar_code){
    //     $html .= '<div id="input_txm"><table  width="100%"  >';
    //     foreach($bar_code as $value){
    //         $html .='<tr><td class="">条形码</td><td><input type="hidden" name="txm_shu[]" value='.$value['taypes'].'>'.$value['taypes'].'<td/><td><input type="text" name="tiaoxingm[]" value='.$value['bar_code'].'></td></tr>';

    //     }
    //     $html .='</table ></div>';
    // }else{
        $html .= '<div id="input_txm"></div>';
    // }



    return $html;
}

/**
 * 取得通用属性和某分类的属性，以及某商品的属性值
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  array   规格与属性列表
 */
function get_attr_list($cat_id, $goods_id = 0)
{
    if (empty($cat_id)) {
        return array();
    }

    // 查询属性值及商品的属性值
    $row = db('goods_attribute')
        -> alias("a")
        -> field('a.attr_id, a.attr_name, a.attr_input_type, a.attr_type,a.attr_txm, a.attr_values, v.attr_value, v.attr_price ')
        -> join("__GOODS_ATTR__ v", "v.attr_id = a.attr_id AND v.goods_id = '$goods_id' ",'LEFT')
        -> where("a.cat_id = " . intval($cat_id) ." OR a.cat_id = 0 ")
        -> order("a.list_order, a.attr_type, a.attr_id, v.attr_price, v.goods_attr_id")
        -> select();
        // pre($row,1);
    return $row;
}
